iT邦幫忙

2022 iThome 鐵人賽

DAY 22
0
Modern Web

clojure 刷刷鍋系列 第 22

Clojure 肉片 -第 22 塊(的一半)

  • 分享至 

  • xImage
  •  

【今日湯底】

Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.

Write a function which takes a list of strings and returns each line prepended by the correct number.

The numbering starts at 1. The format is n: string. Notice the colon and space in between.

Examples: (Input --> Output)

[] --> []
["a", "b", "c"] --> ["1: a", "2: b", "3: c"]

(必須通過以下測試)

(ns line-numbers-test
  (:require [clojure.test :refer :all]
            [line-numbers :refer :all]))
            
(defn tester [lines exp]
  (testing (str "Testing for " lines)
    (is (= (number lines) exp))))
(deftest basic-tests
  (tester [] [])
  (tester ["a" "b" "c"] ["1: a" "2: b" "3: c"])
  (tester ["" "" "" "" ""] ["1: " "2: " "3: " "4: " "5: "]))

【我的答案】

(ns line-numbers)

(defn number [lines]
  (map #(str (inc (.indexOf lines %)) ": " %) lines)
)

可惡,卡在 vector 中出現重複 string 的情境,可能要理解 loop 來使用了,不能用 .indexOf 硬幹XD

【其他人的答案】

還沒解開,今天沒答案可以看,希望明天有時間補完QQ


上一篇
Clojure 肉片 -第 21 塊
下一篇
Clojure 肉片 -第 23 塊
系列文
clojure 刷刷鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言